package com.example.blog.controller;


import com.example.blog.modules.article.dto.FavoriteDTO;
import com.example.blog.service.FavoriteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/favorites")
@CrossOrigin(origins = "*", maxAge = 3600)
public class FavoriteController {
    @Autowired
    private FavoriteService favoriteService;

    @PostMapping("/articles/{articleId}")
    @PreAuthorize("hasRole('USER')")
    public ResponseEntity<FavoriteDTO> favoriteArticle(@PathVariable Long articleId) {
        return ResponseEntity.ok(favoriteService.favoriteArticle(articleId));
    }

    @DeleteMapping("/articles/{articleId}")
    @PreAuthorize("hasRole('USER')")
    public ResponseEntity<?> unfavoriteArticle(@PathVariable Long articleId) {
        favoriteService.unfavoriteArticle(articleId);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/articles/{articleId}/status")
    @PreAuthorize("hasRole('USER')")
    public ResponseEntity<Boolean> hasFavorited(@PathVariable Long articleId) {
        return ResponseEntity.ok(favoriteService.hasFavorited(articleId));
    }

    @GetMapping("/users/{userId}")
    public ResponseEntity<Page<FavoriteDTO>> getUserFavorites(
            @PathVariable Long userId,
            Pageable pageable) {
        return ResponseEntity.ok(favoriteService.getUserFavorites(userId, pageable));
    }

    @GetMapping("/articles/{articleId}")
    public ResponseEntity<Page<FavoriteDTO>> getArticleFavorites(
            @PathVariable Long articleId,
            Pageable pageable) {
        return ResponseEntity.ok(favoriteService.getArticleFavorites(articleId, pageable));
    }

    @GetMapping("/articles/{articleId}/count")
    public ResponseEntity<Long> getArticleFavoritesCount(@PathVariable Long articleId) {
        return ResponseEntity.ok(favoriteService.getArticleFavoritesCount(articleId));
    }
} 